<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书列表</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/art-template/4.13.2/lib/template-web.js"></script>
</head>

<body>
    <h2>图书列表</h2>
    <button onclick="window.location='./add.html'">添加</button>
    <ul></ul>
    <script id="list" type="text/html">
        <% books.forEach(book=>{
            %>
        <li><%=book._id%>---<%=book.name%>---<%=book.author%>---<%=book.price%>
            <button onclick="window.location='./update.html?id=<%=book._id%>'">修改</button>
            <button onclick="deleteBook('<%=book._id%>')">删除</button>
        </li>

        <%
        }) %>
    </script>
    <script>
        // 获取图书列表
        const getBooks = async () => {
            // 解构响应参数
            const {
                data: res
            } = await axios('http://localhost:8080/book')
            // 解构data
            const {
                data: books
            } = res
            // 获取编译后的html
            const html = template('list', {
                books
            })
            // 渲染
            document.querySelector('ul').innerHTML = html
        }

        // 删除指定id的图书
        const deleteBook = async (id) => {
            const {
                data: res
            } = await axios.delete(`http://localhost:8080/book`, {
                params: {
                    id
                }
            })
            if (res.code !== 200) return alert(res.message)
            window.location = './list.html'
        }

        // 当开启该页面的时候立即调用getBooks函数获取图书列表
        getBooks()
    </script>
</body>

</html>